# 根据基础信息生成我自己的userInfo: name,phone,idcard,bankcard

# coding=utf-8

# 1. 查询loanAccount的总数


from pymongo import MongoClient

conn = MongoClient('localhost', 27017)
db = conn.test
index=0

def getloanAmountCount():
    db_account=db.loanAccount
    return db_account.find({}).count()

def getBnakCardByphone(phone):
    return list(db.bankcard.find({"phone":phone}))


def saveUserinFo(userInfos):
    global index
    for info in userInfos:
        info['_id']=index
        index=index+1
    db.userInfo.insert_many(userInfos)


def parsePageData(pageData):
    userInfos=[]
    for data in pageData:
        userInfo={}
        userInfo['name']=str(data['name'])
        phoneBankList=[]
        for phoneData in list(data['phones']):
            phone=str(phoneData['phone'])
            bank=getBnakCardByphone(phone)
            bankCode=''
            if bank :
                bankCode=str(bank[0]['_id'])
            phoneBank={}
            phoneBank['phone']=phone
            phoneBank['bankcard']=bankCode
            phoneBankList.append(phoneBank)
        userInfo['phoneBankList']=phoneBankList
        userInfo['idcard']=str(data['idcard'])
        # print(userInfo)
        userInfos.append(userInfo)
    return userInfos

def getAccountData(count):
    pageSize=2000
    totalPage=1
    if count > pageSize:
        totalPage= int(count/pageSize)+1 if  count%pageSize>0 else count/pageSize


    for page in range(1,totalPage):
      pageData =list(db.loanAccount.find().limit(pageSize).skip((page-1)*pageSize))
      userInfos= parsePageData(pageData)
      saveUserinFo(userInfos)

if __name__=="__main__":
    count=getloanAmountCount()
    getAccountData(count)
